package net.wicp.tams.component.components;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.tapestry5.BindingConstants;
import org.apache.tapestry5.Block;
import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.annotations.AfterRender;
import org.apache.tapestry5.annotations.BeforeRenderTemplate;
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.annotations.InjectService;
import org.apache.tapestry5.json.JSONArray;
import org.apache.tapestry5.json.JSONObject;
import org.apache.tapestry5.services.javascript.JavaScriptSupport;

import net.wicp.tams.component.services.ISupportedLocales;

public class Query {

	@Parameter(value = "prop:componentResources.id", defaultPrefix = BindingConstants.LITERAL)
	@Property
	private String id;
	/****
	 * 查询逻辑
	 */
	@Property
	private Block queryBlock;

	@Parameter(required = false, defaultPrefix = BindingConstants.LITERAL)
	private String qBlock;

	/****
	 * 是否需要翻页，默认需要。
	 */
	@Parameter(required = false, value = "true", defaultPrefix = BindingConstants.LITERAL)
	@Property
	private Boolean pagination;

	/***
	 * 是否单选，默认为是
	 */
	@Parameter(required = false, value = "true", defaultPrefix = BindingConstants.LITERAL)
	@Property
	private boolean singleSelect;

	/****
	 * 新增更新逻辑
	 */
	@Property
	private Block updateBlock;

	@Parameter(required = false, defaultPrefix = BindingConstants.LITERAL)
	private String uBlock;

	@InjectService("locales")
	protected ISupportedLocales supportedLocales;

	/***
	 * 用于查询返回grid数据的地址
	 */
	@Parameter(required = true, defaultPrefix = BindingConstants.LITERAL)
	@Property
	private String queryUrl;

	public boolean isShowUpdateBlock() {
		return resources.isBound("uBlock") && (isShowAdd() || isShowUpdate());
	}

	/***
	 * 格式化op列的函数
	 */
	@Parameter(required = false, value = "opFormatter", defaultPrefix = BindingConstants.LITERAL)
	@Property
	private String opFormatter;

	/***
	 * 显示的列
	 */
	@Parameter(required = true, defaultPrefix = BindingConstants.LITERAL)
	@Property
	private JSONArray columns;
	/***
	 * 定义查询按钮
	 */
	@Parameter(required = false, defaultPrefix = BindingConstants.LITERAL)
	private JSONArray queryButs;

	/***
	 * 定义查询按钮的事件，可以阻拦进行查询
	 */
	@Parameter(required = false, defaultPrefix = BindingConstants.LITERAL)
	@Property
	private String queryHandle;

	/***
	 * 查询成功后的触发事件
	 */
	@Parameter(required = false, defaultPrefix = BindingConstants.LITERAL)
	@Property
	private String loadSuccessHandle;

	/***
	 * datagrid的其余参数
	 */
	@Parameter(required = false, defaultPrefix = BindingConstants.LITERAL)
	private JSONObject params;

	public JSONObject getParams() {
		//
		if (resources.isBound("params")) {
			JSONObject obj = params;
			obj.put("doSize", true);
			return obj;
		} else {
			JSONObject obj = new JSONObject("doSize", true);
			return obj;
		}

	}

	/***
	 * 保存时提交的地址
	 */
	@Parameter(required = false, defaultPrefix = BindingConstants.LITERAL)
	private String saveUrl;

	public String getSaveUrl() {
		return supportedLocales.buildUrl(saveUrl);
	}

	@Parameter(required = false, defaultPrefix = BindingConstants.LITERAL)
	private String deleteUrl;

	public String getDeleteUrl() {
		return supportedLocales.buildUrl(deleteUrl);
	}

	/***
	 * 保存前提交的用户检查
	 */
	@Parameter(required = false, defaultPrefix = BindingConstants.LITERAL)
	@Property
	private String saveCheckHandle;

	/***
	 * 新增时要做的初始化
	 */
	@Parameter(required = false, defaultPrefix = BindingConstants.LITERAL)
	@Property
	private String initAddHandle;

	/***
	 * 修改时要做的初始化
	 */
	@Parameter(required = false, defaultPrefix = BindingConstants.LITERAL)
	@Property
	private String initSaveHandle;

	/***
	 * 保存提交后用户执行的方法
	 */
	@Parameter(required = false, defaultPrefix = BindingConstants.LITERAL)
	@Property
	private String saveReturnHandle;

	@Inject
	protected Messages messages;// 国际化

	/***
	 * grid的标题
	 */
	@Parameter(required = false, defaultPrefix = BindingConstants.LITERAL)
	private String title;

	public String getTitle() {
		if (resources.isBound("title")) {
			return resources.getPage().getComponentResources().getMessages().get(title);
		} else {
			return messages.get("common.label.result");
		}
	}

	/***
	 * dialog对话框的样式
	 */
	@Parameter(required = false, value = "width:500px;height:400px;padding:10px;visibility:hidden;", defaultPrefix = BindingConstants.LITERAL)
	private String dialogStyle;

	public String getDialogStyle() {
		if (resources.isBound("dialogStyle")) {
			String dialogStyleTrue = dialogStyle + (dialogStyle.endsWith(";") ? "" : ";") + "visibility:hidden;";
			return dialogStyleTrue;
		} else {
			return dialogStyle;
		}
	}

	@Inject
	private ComponentResources resources;
	@Environmental
	protected JavaScriptSupport javaScriptSupport;

	public boolean isShowDel() {
		return resources.isBound("deleteUrl");// 显示删除
	}

	public boolean isShowUpdate() {
		return canupdate && resources.isBound("saveUrl");// 显示修改
	}

	public boolean isShowAdd() {
		return canAdd && resources.isBound("saveUrl");// 显示新增
	}

	public boolean isHassaveCheckHandle() {// 是否定义了用户检查的handle
		return resources.isBound("saveCheckHandle");
	}

	public boolean isHassaveReturnHandle() {
		return resources.isBound("saveReturnHandle");
	}

	/***
	 * 是否需要新增按钮
	 */
	@Parameter(required = false, value = "true", defaultPrefix = BindingConstants.LITERAL)
	private boolean canAdd;

	/***
	 * 是否能修改
	 */
	@Parameter(required = false, value = "true", defaultPrefix = BindingConstants.LITERAL)
	private boolean canupdate;

	@AfterRender
	void render() {
		JSONObject spec = new JSONObject();
		spec.put("id", id);
		if (resources.isBound("queryHandle"))
			spec.put("queryHandle", queryHandle);
		if (resources.isBound("initAddHandle"))
			spec.put("initAddHandle", initAddHandle);

		javaScriptSupport.require("init").invoke("queryLayout").with(spec);
	}

	@BeforeRenderTemplate
	void init() {
		// 检查是不是要“操作”列
		if (isShowUpdate() || isShowDel()) {// 如果有修改或删除按钮
			JSONArray jsary = (JSONArray) columns.get(columns.length() - 1);
			JSONObject jsonobj = (JSONObject) jsary.get(jsary.length() - 1);
			if (jsonobj == null || jsonobj.has("field")) {
				if ("op".equalsIgnoreCase(String.valueOf(jsonobj.get("field")))) {
					jsonobj.put("field", "op");// 防止大小写的失误
				} else {// 已有op字段需要设置
					jsary.put(jsary.length(), new JSONObject("field", "op", "width", 150, "title",
							messages.get("common.button.operation")));
				}
			}
		}

		if (resources.isBound("qBlock")) {
			queryBlock = resources.getPage().getComponentResources().getBlock(qBlock);
		}

		if (resources.isBound("uBlock")) {
			updateBlock = resources.getPage().getComponentResources().getBlock(uBlock);
		}

	}

	/****
	 * 查询按钮已在panel2组件中rend
	 */
	// @BeforeRenderTemplate
	public JSONArray getActionButs() {
		List<JSONObject> butList = new ArrayList<JSONObject>();// 需要求的的按钮列表
		List<String> hasButIdList = new ArrayList<String>();// but的id
		if (isShowAdd()) {// 可以新增且有新增的处理函数才出现
			// 添加默认的新增按钮
			String addButIdString = id + "_add";
			butList.add(new JSONObject("id", addButIdString, "iconCls", "icon-add", "text", "common.button.add"));
			hasButIdList.add(addButIdString);
		}
		if (resources.isBound("queryButs")) {// 如果传进来按钮
			for (int i = 0; i < queryButs.length(); i++) {
				JSONObject butObject = queryButs.getJSONObject(i);
				String butIdString = butObject.has("id") ? butObject.getString("id") : "";
				if (StringUtils.isEmpty(butIdString) || !butObject.has("text")) {// 没有id或是text直接跳过
					continue;
				}
				int index = hasButIdList.indexOf(butIdString);
				if (index > -1) {// 通过id更新默认的But
					JSONObject jsonObject = butList.get(index);
					jsonObject.put("id", butObject.getString("id"));
					jsonObject.put("iconCls", butObject.has("iconCls") ? butObject.getString("iconCls") : "");
					jsonObject.put("text", butObject.getString("text"));
					hasButIdList.add(butObject.getString("id"));
					continue;
				}
				butList.add(butObject);
				hasButIdList.add(butObject.getString("id"));
			}
		}
		JSONArray retObj = new JSONArray();
		for (JSONObject but : butList) {
			retObj.put(but);
		}
		return retObj;
	}

	public String getFormClass() {
		return (resources.isBound("queryButs") && queryButs.length() > 0) ? "form_margin" : "no";
	}

}
